//
//  HZMTableDetailsVC.m
//  糖糖大魔王
//
//  Created by 韩震明 on 15/10/27.
//  Copyright © 2015年 韩震明. All rights reserved.
//

#import "HZMTableDetailsVC.h"
#import "HZMItemVC.h"
//#import "JRDataBaseManager.h"

@interface HZMTableDetailsVC ()<UICollectionViewDataSource,UICollectionViewDelegate>

@property(nonatomic, retain) UICollectionView *collection;
@property(nonatomic, retain) NSMutableArray *productArr;
@property(nonatomic, retain) NSMutableArray *picArr;
@property(nonatomic, retain) HZMCHeader *temp;
@property(nonatomic, assign) NSInteger index;

@end

@implementation HZMTableDetailsVC

- (void)dealloc
{
    [_urlStr release];
    [_collection release];
    [_productArr release];
    [_picArr release];
    [_temp release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self navigationSet];
    
    [self createCollectionView];
    
    [self createData];
}



#pragma mark CollectionView Setting
- (void)createCollectionView
{
    UICollectionViewFlowLayout *flowLayout = [[[UICollectionViewFlowLayout alloc] init] autorelease];
    if (self.picArr.count >= 2) {
        flowLayout.itemSize = CGSizeMake(WIDTH - 10, 1 * HEIGHT / 4);
    } else {
        flowLayout.itemSize = CGSizeMake(WIDTH - 10, HEIGHT);
    }
    flowLayout.minimumInteritemSpacing = 1;
    flowLayout.minimumLineSpacing = 1;
    flowLayout.headerReferenceSize = CGSizeMake(WIDTH, 15 * HEIGHT / 31);
    
    if (!self.navigationController.hidesBarsOnSwipe) {
        self.collection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 64) collectionViewLayout:flowLayout];
    } else {
        self.collection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT) collectionViewLayout:flowLayout];
    }
    
    [self.view addSubview:self.collection];
    [_collection release];
    self.collection.backgroundColor = [UIColor whiteColor];
    
    self.collection.delegate = self;
    self.collection.dataSource = self;
    
    [self.collection registerClass:[HZMDetailsCVCell class] forCellWithReuseIdentifier:@"collectionReuse"];
    
    [self.collection registerClass:[HZMCellDetailsCRV class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"c_header_reuse"];
}

#pragma mark - CollectionView Delegate Method
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.productArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    HZMDetailsCVCell *cell = [self.collection dequeueReusableCellWithReuseIdentifier:@"collectionReuse" forIndexPath:indexPath];
    cell.numberLabel.text = [self.productArr[indexPath.row] number];
    cell.titleLabel.text = [self.productArr[indexPath.row] title];
    cell.descLabel.text = (NSString *)[self.productArr[indexPath.row] desc];
    self.picArr = [HZMPic baseModelByArr:(NSMutableArray *)[self.productArr[indexPath.row] pic]];
    [cell.picImageViewHead sd_setImageWithURL:[NSURL URLWithString:[self.picArr[0] pic]] placeholderImage:[UIImage imageNamed:@"back.gif"]];
    cell.priceLabel.text = [self.productArr[indexPath.row] price];
    cell.commentLabel.text = [self.productArr[indexPath.row]  comments];
    cell.likesLabel.text = [self.productArr[indexPath.row] likes];
    
    cell.buyButton.tag = indexPath.row +100000;
    cell.takeModel = ^(NSInteger index)
    {
        HZMBaseWebView *webView = [[HZMBaseWebView alloc] init];
        [self.navigationController pushViewController:webView animated:YES];
        webView.WebViewStrUrl = [self.productArr[indexPath.row] itemUrl];
        webView.titleForWeb = @"宝物详情";
        [webView release];
    };
    cell.productArr = self.productArr[indexPath.row];
//    self.index = indexPath.row;
    
    return cell;
}



- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    HZMItemVC *itemVC = [[HZMItemVC alloc] init];
    itemVC.itsid = [self.productArr[indexPath.row] detailsId];
    [self.navigationController pushViewController:itemVC animated:YES];
    [itemVC release];
}

#pragma mark - CollectionReusableView
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if (kind ==UICollectionElementKindSectionHeader) {
        HZMCellDetailsCRV *reuseableView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"c_header_reuse" forIndexPath:indexPath];
        reuseableView.backgroundColor = [UIColor redColor];
        [reuseableView.topImageView sd_setImageWithURL:[NSURL URLWithString:self.temp.pic]];
        reuseableView.imageViewTitle.text = self.temp.title;
        reuseableView.desc.text = self.temp.desc;
        return reuseableView;
    }
    return nil;
}



#pragma mark Navigation Setting
- (void)navigationSet
{
    self.navigationItem.title = @"专题详情";
    
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.frame = CGRectMake(-20, 0, 40, 40);
    [leftButton setImage:[UIImage imageNamed:@"nav_back@2x.png"] forState:UIControlStateNormal];
    [self.view addSubview:leftButton];
    [leftButton addTarget:self action:@selector(leftBarButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:leftButton] autorelease];
    
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightButton.frame = CGRectMake(0, 0, 40, 40);
    [rightButton setImage:[UIImage imageNamed:@"share_to2"] forState:UIControlStateNormal];
    [self.view addSubview:rightButton];
    [rightButton addTarget:self action:@selector(rightButtonClikl:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:rightButton] autorelease];
    
    self.navigationController.navigationBar.translucent = NO;
}

#pragma mark Navigationbar ButtonAction
- (void)leftBarButtonClick:(UIBarButtonItem *)leftBarButton
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)rightButtonClikl:(UIButton *)rightButton
{
#warning JRDB数据库相关
//    self.topicModel
    [[DataBaseHandle sharDataVaseHandle] openDb];
    [[DataBaseHandle sharDataVaseHandle] createTable];
    
    // 查询数据库, 当前model表中所有数据
//    NSArray *arr1 = [JRDataBaseManager selectTableWithModelClass:[self.topicModel class]];
    // 插入
//    [JRDataBaseManager insertDataWithModel:self.topicModel];
    // 删除
//    [JRDataBaseManager deleteTableWithModelClass:[self.topicModel class] whereKey:@"title" isValue:self.topicModel.title];
    // 修改
//    [JRDataBaseManager updateTableWithModelClass:[self.topicModel class] whereKey:@"name" isValue:@"韩震明" setKeyAndValue:@"sex", @"female", @"height", @"1.44", @"key1", @"value1", nil];
    
    SelectSuper result = [[DataBaseHandle sharDataVaseHandle] isHaveInTable:self.topicModel];
    if (result == InTable) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"已收藏" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"删除" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[DataBaseHandle sharDataVaseHandle] deleteStu:self.topicModel];
            
            
        }];
        [alert addAction:cancel];
        [alert addAction:okAction];
        [self presentViewController:alert animated:YES completion:nil];
    } else if (result == NotInTable) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否收藏" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"收藏" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[DataBaseHandle sharDataVaseHandle] insertStu:self.topicModel];
            
            
        }];
        [alert addAction:cancel];
        [alert addAction:okAction];
        [self presentViewController:alert animated:YES completion:nil];
    } else {
        NSLog(@"收藏失败");
    }
    
}



#pragma mark CreateData
- (void)createData
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:self.urlStr parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSDictionary *dic = responseObject;
        self.temp = [[[HZMCHeader alloc] init] autorelease];
        [self.temp setValuesForKeysWithDictionary:dic[@"data"]];
        
        self.productArr = [NSMutableArray array];
        self.productArr = [HZMItemDetails baseModelByArr:dic[@"data"][@"product"]];
        
        self.picArr = [NSMutableArray array];
        
        [self.collection reloadData];
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        NSLog(@"%@", error);
        
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[DataBaseHandle sharDataVaseHandle] closeDB];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
